package com.powernode.client;

import com.powernode.annotation.Component;

import java.io.File;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class ComponentScan {
    public static void main(String[] args) throws Exception{
        Map<String,Object> beanMap=new HashMap<>();
        String packageName="com.powernode.bean";
        //开始写扫描程序
        String packagePath = packageName.replaceAll("\\.", "/");
        URL url = ClassLoader.getSystemClassLoader().getResource(packagePath);
        String path = url.getPath();
        System.out.println(path);
        File file=new File(path);
        File[] files = file.listFiles();
        Arrays.stream(files).forEach(f->{
            //System.out.println(f.getName().split("\\.")[0]);
            String className=packageName+"."+f.getName().split("\\.")[0];
            //System.out.println(className);
            try {
                Class<?> aClass = Class.forName(className);
                if (aClass.isAnnotationPresent(Component.class)) {
                    Component annotation = aClass.getAnnotation(Component.class);
                    String id = annotation.value();
                    Object obj = aClass.newInstance();
                    beanMap.put(id,obj);
                }
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        });
        System.out.println(beanMap);
    }
}
